﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MODEL;
using MySql.Data.MySqlClient;
using Dapper;

namespace DAL
{
    public class ElementDAL
    {       
        public static async Task<IEnumerable<ElementInfo>> QueryElementsAsync(string stationType)
        {
            string sql = @"SELECT id
                        , elementName
                        , elementCode
                        , stationType
                        , insertEnable
                        FROM msap_db.element_infor
                        WHERE 
                        (@StationType IS NULL OR stationType = @StationType)
                        ORDER BY id DESC";

            using (MySqlConnection conn = new MySqlConnection(AppSetting.Instance.MySqlConnectionStr))
            {
                return await conn.QueryAsync<ElementInfo>(sql, new { StationType = stationType });
            }
        }

        public static async Task<int> InsertElementInfoAsync(ElementInfo element)
        {
            string sql = @"INSERT INTO msap_db.element_infor
                        (
	                        elementName
	                        ,elementCode
                            ,stationType
                            ,insertEnable
                        )
                        values
                        (
	                        @ElementName
	                        ,@ElementCode
                            ,@StationType
                            ,@InsertEnable
                        )";
            using (MySqlConnection conn = new MySqlConnection(AppSetting.Instance.MySqlConnectionStr))
            {
                return await conn.ExecuteAsync(sql, new
                {
                    ElementName = element.ElementName,
                    ElementCode = element.ElementCode,
                    StationType = element.StationType,
                    InsertEnable = element.InsertEnable
                });
            }
        }

        public static async Task<int> DeleteElementInfoAsync(List<int> elementIds)
        {
            string sql = $@"DELETE FROM 
                        msap_db.element_infor 
                        WHERE id IN({string.Join(",", elementIds)}) LIMIT 1";

            using (MySqlConnection conn = new MySqlConnection(AppSetting.Instance.MySqlConnectionStr))
            {
                return await conn.ExecuteAsync(sql);
            }
        }
    }
}
